package com.jhgsys.internal.sypq.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.*;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jhgsys.internal.common.utils.*;
import com.jhgsys.internal.sypq.controller.TaskController;
import com.jhgsys.internal.sypq.entity.*;
import com.jhgsys.internal.sypq.mapper.TaskMapper;
import com.jhgsys.internal.sypq.service.*;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.system.entity.User;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import com.jhgsys.internal.common.entity.FebsConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.jhgsys.internal.sypq.service.impl.ScheduleServiceImpl.mergeDateTime;

/**
 * 任务管理 Service实现
 *
 * @author ganjun
 * @date 2024-11-18 10:06:38
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {
 @Autowired
 ITaskShipService taskShipService;
 @Autowired
    ITaskOarsService  taskOarsService;
 @Autowired
 ITaskAttachService  taskAttachService;
  @Autowired
ITaskTestService taskTestService;
  @Autowired
  ITaskTestcsService taskTestcsService;
  @Autowired
  ITaskTestbl1Service taskTestbl1Service;
    @Autowired
    ITaskTestbl2Service taskTestbl2Service;
    @Autowired
    ITaskTestlxService  taskTestlxService;


  @Autowired
  IWorkflowRecordService workflowRecordService;

  @Autowired
  ISypqProjectService projService;

    @Autowired
    IModelShipService modelShipService;

    @Autowired
    IModelOarsService modelOarsService;

    @Autowired
    IModelAttachService modelAttachService;

    @Autowired
    IResourceService resourceService;

    @Autowired
    INoticeService noticeService;

    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-18 10:06:38
     * @param task task
     * @return List<Task>
     */
    @Override
    public List<Task> findTaskList(Task task) {
	    LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotEmpty(task.getTaskCode())){
            queryWrapper.eq(Task::getTaskCode, task.getTaskCode());
        }
        if(StringUtils.isNotEmpty(task.getRsid())){
            queryWrapper.eq(Task::getRsid, task.getRsid());
        }
        if(task.getStatus() != null){
            queryWrapper.eq(Task::getStatus, task.getStatus());
        }
        queryWrapper.eq(Task::getDeletedFlg, 0);
		return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<TaskDto> findTaskPage(QueryRequest request, TaskDto taskDto,String userid) {
        // TODO 设置查询条件
        Page<Task> page = new Page<>(request.getPageNum(), request.getPageSize());
        IPage<TaskDto>  result= this.baseMapper.getTaskDetailPage(page, taskDto,userid);
         List<TaskDto>  list= result.getRecords();
         list.forEach(obj->{
             if(obj.getTaskType()==1){
                 TaskTest taskTest=new TaskTest();
                 taskTest.setTaskcode(obj.getTaskCode());
                 List<TaskTest> taskTestList=this.taskTestService.findTaskTestList(taskTest);
                 obj.setTaskTestArray(JSON.parseArray(JSON.toJSONString(taskTestList)));
             }else  if(obj.getTaskType()==2){
                 TaskTestcs test=new TaskTestcs();
                 test.setTaskcode(obj.getTaskCode());
                 List<TaskTestcs> taskTestcsList=taskTestcsService.findTaskTestcsList(test);
                 obj.setTaskTestcsArray(JSON.parseArray(JSON.toJSONString(taskTestcsList)));
             }else if(obj.getTaskType()==3){
                 TaskTestbl1 test1=new TaskTestbl1();
                 test1.setTaskcode(obj.getTaskCode());
                 List<TaskTestbl1> taskTestbl1sList=taskTestbl1Service.findTaskTestbl1List(test1);
                 obj.setTaskTestbl1Array(JSON.parseArray(JSON.toJSONString(taskTestbl1sList)));
                 TaskTestbl2 test2=new TaskTestbl2();
                 test2.setTaskcode(obj.getTaskCode());
                 List<TaskTestbl2> taskTestbl2sList=taskTestbl2Service.findTaskTestbl2List(test2);
                 obj.setTaskTestbl2Array(JSON.parseArray(JSON.toJSONString(taskTestbl2sList)));
             }else if(obj.getTaskType()==4){
                 TaskTestlx test=new TaskTestlx();
                 test.setTaskcode(obj.getTaskCode());
                 List<TaskTestlx> taskTestlxList=taskTestlxService.findTaskTestlxList(test);
                 obj.setTaskTestlxArray(JSON.parseArray(JSON.toJSONString(taskTestlxList)));
             }
         });
         result.setRecords(list);
        return  result;

    }

    @Override
    public List<TaskDto> findTaskList(TaskDto taskDto) {
         List<TaskDto>  list=this.baseMapper.getTaskDetail(taskDto,"");
         for(TaskDto  dto:list){
             if(org.apache.commons.lang3.StringUtils.isNotBlank(dto.getFileinfo())){
                 dto.setFileList(JSON.parseArray(dto.getFileinfo()));
             }
         }
       list=list.stream().map(obj->{
            if(obj.getTaskType()==1){
                TaskTest taskTest=new TaskTest();
                taskTest.setTaskcode(obj.getTaskCode());
                List<TaskTest> taskTestList=this.taskTestService.findTaskTestList(taskTest);
                obj.setTaskTestArray(JSON.parseArray(JSON.toJSONString(taskTestList)));
            }else  if(obj.getTaskType()==2){
                TaskTestcs test=new TaskTestcs();
                test.setTaskcode(obj.getTaskCode());
                List<TaskTestcs> taskTestcsList=taskTestcsService.findTaskTestcsList(test);
                obj.setTaskTestcsArray(JSON.parseArray(JSON.toJSONString(taskTestcsList)));
            }else if(obj.getTaskType()==3){
                TaskTestbl1 test1=new TaskTestbl1();
                test1.setTaskcode(obj.getTaskCode());
                List<TaskTestbl1> taskTestbl1sList=taskTestbl1Service.findTaskTestbl1List(test1);
                obj.setTaskTestbl1Array(JSON.parseArray(JSON.toJSONString(taskTestbl1sList)));
                TaskTestbl2 test2=new TaskTestbl2();
                test2.setTaskcode(obj.getTaskCode());
                List<TaskTestbl2> taskTestbl2sList=taskTestbl2Service.findTaskTestbl2List(test2);
                obj.setTaskTestbl2Array(JSON.parseArray(JSON.toJSONString(taskTestbl2sList)));
            }else if(obj.getTaskType()==4){
                TaskTestlx test=new TaskTestlx();
                test.setTaskcode(obj.getTaskCode());
                List<TaskTestlx> taskTestlxList=taskTestlxService.findTaskTestlxList(test);
                obj.setTaskTestlxArray(JSON.parseArray(JSON.toJSONString(taskTestlxList)));
            }

             WorkflowRecord workflowRecord=new WorkflowRecord();
             workflowRecord.setVoucherType("7");
             workflowRecord.setVoucherId(taskDto.getTaskCode());
            List<WorkflowRecord> workflowRecordList=this.workflowRecordService.findWorkflowRecordList(workflowRecord);

            obj.setWorkflowArray(JSON.parseArray(JSON.toJSONString(workflowRecordList)));
            if(StringUtils.isNotEmpty(obj.getShipcodes())&& obj.getShipcodes().endsWith(",")){
                obj.setShipcodes(obj.getShipcodes().substring(0,obj.getShipcodes().length()-1));
            }
            return obj;
        }).collect(Collectors.toList());
        return  list;
    }


    /**
    * 根据ID查询
    * @author ganjun
    * @date 2024-11-18 10:06:38
    * @param id
    * @return Task
    */
    @Override
    public Task findTaskById(String id){
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     * @author ganjun
     * @date 2024-11-18 10:06:38
     * @param task task
     */
    @Override
    @Transactional
    public boolean createTask(TaskDto taskDto) {
        if(StringUtils.isBlank(taskDto.getIskeyTask())){
            taskDto.setIskeyTask("0");
        }
        Task task = BeanHelper.copyProperties(taskDto, Task.class);
        task.setFileinfo("");
        if(!ObjectUtils.isEmpty(taskDto.getFileList())){
            task.setFileinfo(JSON.toJSONString(taskDto.getFileList()));
        }
        task.setDeletedFlg("0");
        if(task.getTaskType()==1){
            task.setStatus(1);
        }else {
            task.setStatus(8);
        }

        //保存船模.桨模。附体
        String  modelids=taskDto.getModelids();
        saveTaskModel(modelids,taskDto.getTaskCode());
        //保存测试内容
        if(1==taskDto.getTaskType()){
            JSONArray taskTestArray= taskDto.getTaskTestArray();
            saveTaskTest(taskTestArray, taskDto.getTaskCode());
        }else  if(2==taskDto.getTaskType()){
            JSONArray taskTestcsArray=taskDto.getTaskTestcsArray();
            saveTaskTestcs(taskTestcsArray, taskDto.getTaskCode());
        }else if(3==taskDto.getTaskType()){
            JSONArray taskTestbl1Array=taskDto.getTaskTestbl1Array();
            saveTaskTestbl1(taskTestbl1Array, taskDto.getTaskCode());
            JSONArray taskTestbl2Array=taskDto.getTaskTestbl2Array();
            saveTaskTestbl2(taskTestbl2Array, taskDto.getTaskCode());
        } if(4==taskDto.getTaskType()){
            JSONArray taskTestlxArray=taskDto.getTaskTestlxArray();
            saveTaskTestlx(taskTestlxArray, taskDto.getTaskCode());
        }
        boolean result= this.save(task);
        //向审批流表中插入记录
         return  result;
    }


    private  void  saveTaskModel(String modelids,String taskcode){
        List<String> shipModels=new ArrayList<>();
        List<String> oarsModels=new ArrayList<>();
        List<String> attachModels=new ArrayList<>();
        if(StringUtils.isNotEmpty(modelids)){
            String[]  ids=modelids.split(",");
            for(String id:ids){
                if(id.startsWith("cm_")){
                    shipModels.add(id.substring(3));
                }else if(id.startsWith("jm_")){
                    oarsModels.add(id.substring(3));
                }else if(id.startsWith("ft_")){
                    attachModels.add(id.substring(3));
                }
            }
        }
        for(String code:shipModels){
            TaskShip taskShip=new TaskShip();
            taskShip.setShipCode(code);
            taskShip.setTaskCode(taskcode);
            taskShip.setDeletedFlg("0");
            this.taskShipService.save(taskShip);
        }

        for(String code:oarsModels){
            TaskOars taskOars=new TaskOars();
            taskOars.setOarsCode(code);
            taskOars.setTaskCode(taskcode);
            taskOars.setDeletedFlg("0");
            this.taskOarsService.save(taskOars);
        }

        for(String code:attachModels){
            TaskAttach taskAttach=new TaskAttach();
            taskAttach.setAttachCode(code);
            taskAttach.setTaskCode(taskcode);
            taskAttach.setDeletedFlg("0");
            this.taskAttachService.save(taskAttach);
        }
     }


    private  void  saveTaskTest(JSONArray taskTestArray,String taskcode){
        if(taskTestArray==null){
            return;
        }
        List<TaskTest> taskTestList=new ArrayList<>();
       for(int i=0;i<taskTestArray.size();i++){
           JSONObject jsonObject=taskTestArray.getJSONObject(i);
           TaskTest taskTest=new TaskTest();
           taskTest.setTaskcode(taskcode);
           taskTest.setNo(jsonObject.getInteger("no"));
           taskTest.setResistance(jsonObject.getString("resistance"));
           taskTest.setNavigate(jsonObject.getString("navigate"));
           taskTest.setSeakeep(jsonObject.getString("seakeep"));
           taskTest.setControll(jsonObject.getString("controll"));
           taskTest.setDeletedFlg("0");
           taskTestList.add(taskTest);
       }
       taskTestService.saveBatch(taskTestList);
    }

    private  void  saveTaskTestcs(JSONArray taskTestcsArray,String taskcode){
        if(taskTestcsArray==null){
            return;
        }
        for(int i=0;i<taskTestcsArray.size();i++){
            JSONObject jsonObject=taskTestcsArray.getJSONObject(i);
            TaskTestcs obj=new TaskTestcs();
            obj.setTaskcode(taskcode);
            obj.setOarsCode(jsonObject.getString("oarsCode"));
            obj.setDiameter(jsonObject.getString("diameter"));
            obj.setChord(jsonObject.getString("chord"));
            obj.setLeaf(jsonObject.getString("leaf"));
            obj.setPitch(jsonObject.getString("pitch"));
            obj.setRemark(jsonObject.getString("remark"));
            obj.setSurface(jsonObject.getString("surface"));
            obj.setDeletedFlg("0");
            if(jsonObject.getInteger("id")==null||jsonObject.getInteger("id")==0){
                taskTestcsService.save(obj);
            }else{
                obj.setId(jsonObject.getInteger("id"));
                taskTestcsService.updateById(obj);
            }
        }
    }


    private  void  saveTaskTestlx(JSONArray taskTestlxArray,String taskcode){
        if(taskTestlxArray==null){
            return;
        }
        for(int i=0;i<taskTestlxArray.size();i++){
            JSONObject jsonObject=taskTestlxArray.getJSONObject(i);
            TaskTestlx obj=new TaskTestlx();
            obj.setTaskcode(taskcode);
            obj.setShipcode(jsonObject.getString("shipcode"));
            obj.setDraugh(jsonObject.getString("draugh"));
            obj.setDisplacement(jsonObject.getString("displacement"));
            obj.setSpeed(jsonObject.getString("speed"));
            obj.setRemark(jsonObject.getString("remark"));
            obj.setDeletedFlg("0");
            if(jsonObject.getInteger("id")==null||jsonObject.getInteger("id")==0){
                taskTestlxService.save(obj);
            }else{
                obj.setId(jsonObject.getInteger("id"));
                taskTestlxService.updateById(obj);
            }
        }
    }

    private  void  saveTaskTestbl1(JSONArray taskTestbl1Array,String taskcode){
        if(taskTestbl1Array==null){
            return;
             }
        for(int i=0;i<taskTestbl1Array.size();i++){
            JSONObject jsonObject=taskTestbl1Array.getJSONObject(i);
            TaskTestbl1 obj=new TaskTestbl1();
            obj.setTaskcode(taskcode);
            obj.setShipCode(jsonObject.getString("shipCode"));
            obj.setDraugh(jsonObject.getString("draugh"));
            obj.setDisplacement(jsonObject.getString("displacement"));
            obj.setSpeed(jsonObject.getString("speed"));
            obj.setRemark(jsonObject.getString("remark"));
            obj.setDeletedFlg("0");
            if(jsonObject.getInteger("id")==null||jsonObject.getInteger("id")==0){
                taskTestbl1Service.save(obj);
            }else{
                obj.setId(jsonObject.getInteger("id"));
                taskTestbl1Service.updateById(obj);
            }
        }
    }

    private  void  saveTaskTestbl2(JSONArray taskTestbl2Array,String taskcode){
        if(taskTestbl2Array==null){
            return;
        }
        for(int i=0;i<taskTestbl2Array.size();i++){
            JSONObject jsonObject=taskTestbl2Array.getJSONObject(i);
            TaskTestbl2 obj=new TaskTestbl2();
            obj.setTaskcode(taskcode);
            obj.setOarsCode(jsonObject.getString("oarsCode"));
            obj.setDiameter(jsonObject.getString("diameter"));
            obj.setSurface(jsonObject.getString("surface"));
            obj.setDirect(jsonObject.getString("direct"));
            obj.setRemark(jsonObject.getString("remark"));
            obj.setDeletedFlg("0");
            if(jsonObject.getInteger("id")==null||jsonObject.getInteger("id")==0){
                taskTestbl2Service.save(obj);
            }else{
                obj.setId(jsonObject.getInteger("id"));
                taskTestbl2Service.updateById(obj);
            }
        }
    }
    /**
     * 修改
     * @author ganjun
     * @date 2024-11-18 10:06:38
     * @param task task
     */
    @Override
    @Transactional
    public boolean updateTask(TaskDto taskDto) {
        if(StringUtils.isBlank(taskDto.getIskeyTask())){
            taskDto.setIskeyTask("0");
        }
        Task task = BeanHelper.copyProperties(taskDto, Task.class);
        task.setFileinfo("");
        if(!ObjectUtils.isEmpty(taskDto.getFileList())){
            task.setFileinfo(JSON.toJSONString(taskDto.getFileList()));
        }
        task.setDeletedFlg("0");

        //比较模型.资源和工时是否发生变化，如发生变化，对于已排期任务，则需要重新排期
        List<TaskDto> list = this.findTaskList(taskDto);
        if(list.size()>0){
            TaskDto   oldtask=list.get(0);
            if(oldtask.getTaskType()==1 && (oldtask.getStatus()==4||oldtask.getStatus()==5)&&
               (oldtask.getModelids()==null&&taskDto.getModelids()!=null ||
               oldtask.getModelids()!=null &&taskDto.getModelids()==null
                ||!oldtask.getModelids().equals(taskDto.getModelids()) ||
               oldtask.getRsid()==null &&taskDto.getRsid()!=null ||
               oldtask.getRsid()!=null && taskDto.getRsid()==null ||
                !oldtask.getRsid().equals(taskDto.getRsid())||
               oldtask.getTestDay()==null && taskDto.getTestDay()!=null||
                oldtask.getTestDay()!=null && taskDto.getTestDay()==null||
                oldtask.getTestDay().floatValue()!=taskDto.getTestDay().floatValue())){
                  task.setStatus(1);
                  task.setPlanStartdate(null);
                  task.setPlanEnddate(null);
                  task.setPlanEnddate(null);
                  task.setPlanEndtime(null);
               }
        }
        //保存船模.桨模。附体
        taskShipService.physicallyDeleteByTaskcode(taskDto.getTaskCode());
        taskOarsService.physicallyDeleteByTaskcode(taskDto.getTaskCode());
        taskAttachService.physicallyDeleteByTaskcode(taskDto.getTaskCode());
        taskTestService.physicallyDeleteByTaskcode(taskDto.getTaskCode());
        String  modelids=taskDto.getModelids();
        saveTaskModel(modelids,taskDto.getTaskCode());
        if(1==taskDto.getTaskType()){
            JSONArray taskTestArray= taskDto.getTaskTestArray();
            saveTaskTest(taskTestArray, taskDto.getTaskCode());
        }else  if(2==taskDto.getTaskType()){
            JSONArray taskTestcsArray=taskDto.getTaskTestcsArray();
            saveTaskTestcs(taskTestcsArray, taskDto.getTaskCode());
        }else if(3==taskDto.getTaskType()){
            JSONArray taskTestbl1Array=taskDto.getTaskTestbl1Array();
            saveTaskTestbl1(taskTestbl1Array, taskDto.getTaskCode());
            JSONArray taskTestbl2Array=taskDto.getTaskTestbl2Array();
            saveTaskTestbl2(taskTestbl2Array, taskDto.getTaskCode());
        } if(4==taskDto.getTaskType()){
            JSONArray taskTestlxArray=taskDto.getTaskTestlxArray();
            saveTaskTestlx(taskTestlxArray, taskDto.getTaskCode());
        }
         //系统更新planStartdate.planStarttime.planEnddate.planEndtime不成功
        return this.updateById(task);
    }

    /**
     * 逻辑删除
     * @author ganjun
     * @date 2024-11-18 10:06:38
     * @param task task
     * @param taskIds taskIds
     */
    @Override
    @Transactional
    public boolean deleteTask(Task task,String taskIds) {
        boolean result = false;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> list = Arrays.asList(taskIds.split(StringPool.COMMA));

        task.setDeletedBy(user.getUserName());
        task.setDeletedTime(new Date());
        task.setDeletedFlg(FebsConstant.INVALID);
        int update = this.baseMapper.update(task,new LambdaQueryWrapper<Task>().in(Task::getTaskCode,list));
        if (update > 0 ){
            result = true;
        }
        return result;
	}

    /**
    * 物理删除
    * @author ganjun
    * @date 2024-11-18 10:06:38
    * @param taskIds taskIds
    */
    @Override
    @Transactional
    public boolean physicallyDeleteTask(String taskIds) {
        List<String> list = Arrays.asList(taskIds.split(StringPool.COMMA));
        LambdaQueryWrapper<Task> wapper = new LambdaQueryWrapper<>();
        wapper.in(Task::getTaskCode,list);
        return this.remove(wapper);
    }

    @Override
    public String  getNewTaskcode(){
        String prefix= "TK" + DateUtil.getDateFormat(new Date(), "yyyyMM");
        String maxSerialNo= baseMapper.getMaxSerialNo(prefix);
        if(StringUtils.isNotEmpty(maxSerialNo)){
            maxSerialNo=maxSerialNo.substring(8,12);
            if(maxSerialNo.matches("\\d{4}")){
                Integer   serialno=(Integer.valueOf(maxSerialNo)+10001);
                return  prefix+String.valueOf(serialno).substring(1);
            }else {
                return prefix+"0001";
            }
        }else {
            return   prefix+"0001";
        }
    }




    @Override
    public  List<TaskModelDto>  getModelListByProjectcode(String   projectCode,String taskCode){
        return   this.baseMapper.getModelListByProjectcode(projectCode,taskCode);
    }
    /**
     * 自动完成正常清空的任务
     */
    @Override
    public void autoFinishTask() {
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getDeletedFlg, 0);
        queryWrapper.eq(Task::getStatus, 5);
        List<Task> taskList = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(taskList)) {

            for (Task t : taskList) {
                if (t != null && t.getActuallyEnddate() != null && DateUtil.compareWithNow(t.getActuallyEnddate()) == 0) {
                    //更新状态为已完成
                    t.setStatus(6);
                    baseMapper.updateById(t);
                    //判断所属项目下的所有任务是否都已完成，如果已完成，则将项目更新为已完成
                    String projectCode = t.getProjectCode();
                    LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Task::getDeletedFlg, 0);
                    wrapper.eq(Task::getProjectCode, projectCode);
                    List<Task> sameProjTasks = this.baseMapper.selectList(wrapper);
                    boolean allFinished = true;
                    if (CollectionUtil.isNotEmpty(sameProjTasks)) {
                        for (Task task : sameProjTasks) {
                            if (6 != task.getStatus()) {
                                allFinished = false;
                                break;
                            }
                        }
                    }
                    //项目中的任务全部为完成状态，更新项目状态
                    if (allFinished) {
                        SypqProject sypqProject = new SypqProject();
                        sypqProject.setProjectCode(projectCode);
                        List<SypqProject> projList = projService.findSypqProjectList(sypqProject);
                        if (CollectionUtil.isNotEmpty(projList)) {
                            SypqProject proj = projList.get(0);
                            if (proj != null) {
                                proj.setStatus(7);
                            }
                            projService.updateById(proj);
                        }
                    }
                }
            }
        }
    }


    @Override
    public void remindPendingTask(){
        //一周后的起、止时间
        Date queryDate = DateUtil.getPastDate(new Date(), 7);
        String startTime = DateUtil.getDateFormat(queryDate, DateUtil.YYYY_MM_DD_PATTERN) + " 00:00:00";
        String endTime = DateUtil.getDateFormat(queryDate, DateUtil.YYYY_MM_DD_PATTERN) + " 23:59:59";
        //获取排期任务
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getDeletedFlg, 0);
        queryWrapper.eq(Task::getTaskType, 1);
        queryWrapper.notIn(Task::getStatus, 5,6,7,8);
        queryWrapper.between(Task::getPlanStartdate, startTime, endTime);
        List<Task> taskList = this.baseMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(taskList)){
            for(Task task : taskList){
                if(task != null){
                    String taskCode = task.getTaskCode();
                    boolean isReady = true;
                    //获取任务中的船模
                    TaskShip taskShip = new TaskShip();
                    taskShip.setTaskCode(taskCode);
                    List<TaskShip> taskShipList = taskShipService.findTaskShipList(taskShip);
                    if(CollectionUtil.isNotEmpty(taskShipList)){
                        for(TaskShip ts : taskShipList){
                            ModelShip modelShip = new ModelShip();
                            modelShip.setShipCode(ts.getShipCode());
                            List<ModelShip> modelShipList = modelShipService.findModelShipList(modelShip);
                            if(CollectionUtil.isNotEmpty(modelShipList)){
                                for(ModelShip ms : modelShipList){
                                    if(ms != null && ms.getActuallyEnddate() == null){
                                        isReady = false;
                                        break;
                                    }
                                }
                            }
                            if(!isReady){
                                break;
                            }
                        }

                    }
                    if(isReady){
                        //获取任务中的桨模
                        TaskOars taskOars = new TaskOars();
                        taskOars.setTaskCode(taskCode);
                        List<TaskOars> taskOarsList = taskOarsService.findTaskOarsList(taskOars);
                        if(CollectionUtil.isNotEmpty(taskOarsList)){
                            for(TaskOars to : taskOarsList){
                                ModelOars modelOars = new ModelOars();
                                modelOars.setOarsCode(to.getOarsCode());
                                List<ModelOars> oarsList = modelOarsService.findModelOarsList(modelOars);
                                if(CollectionUtil.isNotEmpty(oarsList)){
                                    for(ModelOars mo : oarsList){
                                        if(mo != null && mo.getActuallyEnddate() == null){
                                            isReady = false;
                                            break;
                                        }
                                    }
                                }
                                if(!isReady){
                                    break;
                                }
                            }
                        }
                    }
                    if(isReady){
                        //获取任务中的附体
                        TaskAttach taskAttach = new TaskAttach();
                        taskAttach.setTaskCode(taskCode);
                        List<TaskAttach> taskAttachList = taskAttachService.findTaskAttachList(taskAttach);
                        if(CollectionUtil.isNotEmpty(taskAttachList)){
                            for(TaskAttach ta : taskAttachList){
                                ModelAttach modelAttach = new ModelAttach();
                                modelAttach.setAttachCode(ta.getAttachCode());
                                List<ModelAttach> modelAttachList = modelAttachService.findModelAttachList(modelAttach);
                                if(CollectionUtil.isNotEmpty(modelAttachList)){
                                    for(ModelAttach ma : modelAttachList){
                                        if(ma != null && ma.getActuallyEnddate() == null){
                                            isReady = false;
                                            break;
                                        }
                                    }
                                }
                                if(!isReady){
                                    break;
                                }
                            }
                        }
                    }
                    //判断是否发待办
                    if(!isReady){
                        String rsId = task.getRsid();
                        Resource resource = resourceService.findResourceById(rsId);
                        Notice notice = new Notice();
                        notice.setNoticeType(1);
                        notice.setNoticeTitle("任务不完备提醒");
                        notice.setNoticeContent("您有一条任务【" + task.getTaskCode() + "】不完备提醒！");
                        notice.setReceiveUserId(resource.getRsDirector());
                        notice.setReceiveRealName(resource.getRsDirectorName());
                        notice.setSendDate(new Date());
                        noticeService.createNotice(notice);
                    }
                }
            }
        }
    }



    @Override
    public void autoStartTask() {
        LambdaQueryWrapper<Task> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Task::getDeletedFlg, 0);
        queryWrapper.eq(Task::getStatus, 4);
        List<Task> taskList = this.baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(taskList)) {
             for(Task task:taskList){
                 //计划开始时间到期，更新实际开始时间
                 Date plantime=ScheduleServiceImpl.mergeDateTime(task.getPlanStartdate(),task.getPlanStarttime());
                if((new Date()).getTime()>plantime.getTime()){
                    task.setActuallyStartdate(plantime);
                    task.setStatus(5);
                    this.baseMapper.updateById(task);
                }
                //更新项目实际开始时间
                String projectcode=   task.getProjectCode();
                SypqProject sypqProject=projService.findSypqProjectById(projectcode);
                if(sypqProject.getStatus()==4||sypqProject.getStatus()==5){
                    sypqProject.setStatus(6);
                    sypqProject.setActualStartdate(plantime);
                    this.projService.updateById(sypqProject);
                }
             }
        }
    }

    @Override
    public   String  checkTask(Task task){
        StringBuffer  sb=new StringBuffer();
        List  list=findTaskList(task);
        if(list.size()>0){
            sb.append("任务编码已存在!");
        }
        return  sb.toString();
    }

    public void completeNonScheduleTask(TaskDto taskDto){
        Task  task=baseMapper.selectById(taskDto.getTaskCode());
        task.setActuallyStartdate(mergeDateTime(taskDto.getPlanStartdate(),taskDto.getPlanStarttime()));
        task.setActuallyEnddate(mergeDateTime(taskDto.getPlanEnddate(),taskDto.getPlanEndtime()));
        //计算testday
       float  testday=(float) (taskDto.getPlanEnddate().getTime()-taskDto.getPlanStartdate().getTime())/(24*60*60*1000);
       if("12:00".equals(DateUtils.format(taskDto.getPlanStarttime(), "HH:mm"))){
           testday=testday-0.5f;
       }
        if("12:00".equals(DateUtils.format(taskDto.getPlanEndtime(), "HH:mm"))){
            testday=testday-0.5f;
        }
         task.setTestDay(new BigDecimal(testday + 1));
        task.setStatus(6);
        this.baseMapper.updateById(task);
    }
}
